import React, { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, Toast } from "antd-mobile";
import useCountDown from "../../hooks/useCountDown";
import http from "../../utils/http";

const TelIndex = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { countDown, isRuning, startCountDown } = useCountDown(10);

  const codeText = useMemo(() => {
    if (isRuning) {
      return `${countDown}秒后重新发送`;
    } else {
      return "获取验证码";
    }
  }, [countDown]);

  //点击发送验证码按钮
  const handelEmitCode = () => {
    //点击发送验证码按钮时，先校验手机号是否正确
    form.validateFields(["tel"]).then(async ({ tel }) => {
      //开始倒计时
      startCountDown();
      //请求获取验证码接口
      const res = await http.get("/api/login/code", {
        params: { tel },
      });

      const { code, data } = res.data;
      if (code === 200) {
        Toast.show("验证码获取成功");
        //给验证码的input赋值
        form.setFieldValue("telCode", data);
      } else {
        Toast.show("验证码获取失败");
      }
    });
  };

  //提交表单
  const onFinish = async (values) => {
    const res = await http.post("/api/login/tel", values);
    const { code, data } = res.data;
    if (code === 200) {
      Toast.show("登陆成功");
      localStorage.setItem("token", data.token);
      localStorage.setItem("userInfo", data.userInfo);
      navigate("/");
    }
  };

  return (
    <div>
      <Form
        form={form}
        onFinish={onFinish}
        layout="horizontal"
        mode="card"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>火车票登陆系统</Form.Header>
        <Form.Item
          name="tel"
          label="用户名"
          rules={[
            {
              required: true,
              message: "用户名输入格式不正确",
              pattern: /^1[3-9]\d{9}$/,
              //pattern: /\w+@\w+\.\w+/,
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          name="telCode"
          rules={[
            {
              required: true,
              message: "验证码输入不能为空",
            },
          ]}
          label="短信验证码"
          extra={
            <Button
              disabled={isRuning ? true : false}
              size="mini"
              onClick={() => handelEmitCode()}
            >
              {codeText}
            </Button>
          }
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default TelIndex;
